package commons
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.events.Event;

	import commons.cache.SourceCache;

	import events.loader.CacheEvent;

	/**
	 * 图片元件
	 * @author Dont小鬼
	 * 2014-9-2
	 */

	public class ImgBitmap extends Bitmap
	{
		/**加载图片完成**/
		public static const LoadPicCom:String  = "ImgBitmap.LoadPicCom";

		private var _picUrl:String;

		public function ImgBitmap(picUrl:String = "")
		{
			_picUrl = picUrl;
			super();
			loadImg();
		}

		/**
		 * 设置图片
		 * @param picUrl
		 */
		public function setImg(picUrl:String):void
		{
			_picUrl = picUrl;
			loadImg();
		}

		/**
		 * 加载图片
		 */
		private function loadImg():void
		{
			if (_picUrl == "")
				return;

			if (SourceCache.getInstance().has(_picUrl))
			{
				this.bitmapData = (SourceCache.getInstance().getObject(_picUrl) as BitmapData).clone();
				this.dispatchEvent(new Event(LoadPicCom));
			}
			else
			{
				SourceCache.getInstance().addEventListener(Event.COMPLETE
					, onResLoaderCompleteHandler);
				if (SourceCache.getInstance().isLoading(_picUrl) == false)
				{
					SourceCache.getInstance().load(_picUrl, true);
				}
			}
		}

		/**
		 * 加载图片完成
		 * @param evt
		 */
		private function onResLoaderCompleteHandler(evt:CacheEvent):void
		{
			if (evt.url == _picUrl)
			{
				SourceCache.getInstance().removeEventListener(Event.COMPLETE
					, onResLoaderCompleteHandler);
				this.bitmapData = (SourceCache.getInstance().getObject(_picUrl) as BitmapData).clone();
				this.dispatchEvent(new Event(LoadPicCom));
			}
		}
	}
}


